import React, { useState, useEffect, useCallback } from 'react';
import { Form, Input, Select, DatePicker, Button, Table, Pagination, Space, Tag, message } from 'antd';
import type { ColumnsType } from 'antd/es/table';
import type { TablePaginationConfig, FilterValue, SorterResult } from 'antd/es/table/interface';
import axios from 'axios';

const { Option } = Select;
const { RangePicker } = DatePicker;

interface DataType {
  key: string;
  id: number;
  userCode: string;
  type: string;
  paymentMethod: string;
  amount: number;
  remaining: number;
  operationRemark: string;
  waybillNumber: string;
  packageName: string;
  packageDetail: string;
  itemDetail: string;
}

interface SearchFormValues {
  searchField?: string;
  matchValue?: string;
  dateRange?: [string, string];
  type?: string;
}

interface ValidateErrorEntity {
  // eslint-disable-next-line @typescript-eslint/no-explicit-any
  values: any;
  errorFields: { name: string | number | (string | number)[]; errors: string[] }[];
  outOfDate: boolean;
}

const Financialdetails: React.FC = () => {
  const [form] = Form.useForm();
  const [data, setData] = useState<DataType[]>([]);
  const [pagination, setPagination] = useState({
    current: 1,
    pageSize: 10,
    total: 0,
  });

  const fetchData = useCallback(async (page: number, pageSize: number, searchValues?: SearchFormValues) => {
    message.loading('正在加载数据...', 0);
    const values = searchValues || form.getFieldsValue();
    const params = {
      currentPage: page,
      pageSize: pageSize,
      searchField: values.searchField,
      searchValue: values.matchValue,
      startTime: values.dateRange && values.dateRange[0] ? values.dateRange[0].format('YYYY-MM-DD HH:mm:ss') : undefined,
      endTime: values.dateRange && values.dateRange[1] ? values.dateRange[1].format('YYYY-MM-DD HH:mm:ss') : undefined,
      type: values.type === 'all' ? undefined : values.type,
    };

    try {
      const response = await axios.get('http://localhost:5233/api/Financialdetails/GetFinancialdetails', { params });
      message.destroy();
      if (response.data.success) {
        console.log("查询到的数据",response.data.data.list);
        // eslint-disable-next-line @typescript-eslint/no-explicit-any
        setData(response.data.data.list.map((item: any) => ({ ...item, key: item.id.toString() })));
        setPagination(prev => ({
          ...prev,
          current: page,
          pageSize: pageSize,
          total: response.data.data.total,
        }));
        message.success('数据加载成功！');
      } else {
        message.error(response.data.message || '获取数据失败！');
      }
    } catch (error) {
      console.error('获取数据失败:', error);
      message.destroy();
      message.error('获取数据失败，请检查网络或服务器！');
    }
  }, [form]);

  useEffect(() => {
    fetchData(pagination.current, pagination.pageSize);
  }, [fetchData, pagination.current, pagination.pageSize]);

  const columns: ColumnsType<DataType> = [
    {
      title: '序号',
      dataIndex: 'id',
      key: 'id',
    },
    {
      title: '用户编码',
      dataIndex: 'userCode',
      key: 'userCode',
    },
    {
      title: '类型',
      dataIndex: 'type',
      key: 'type',
      render: (text: string) => (
        <Tag color={text === '充值' ? 'green' : (text === '消费' ? 'red' : 'blue')}>
          {text}
        </Tag>
      ),
    },
    {
      title: '支付方式',
      dataIndex: 'paymentMethod',
      key: 'paymentMethod',
    },
    {
      title: '金额(元)',
      dataIndex: 'amount',
      key: 'amount',
      render: (text: number) => (
        <span style={{ color: text > 0 ? 'green' : 'red' }}>{text.toFixed(2)}</span>
      ),
    },
    {
      title: '剩余',
      dataIndex: 'remaining',
      key: 'remaining',
    },
    {
      title: '操作备注',
      dataIndex: 'operationRemark',
      key: 'operationRemark',
    },
    {
      title: '运单号',
      dataIndex: 'waybillNumber',
      key: 'waybillNumber',
    },
    {
      title: '包裹名称',
      dataIndex: 'packageName',
      key: 'packageName',
    },
    {
      title: '包裹详情',
      dataIndex: 'packageDetail',
      key: 'packageDetail',
    },
    {
      title: '物品详情',
      dataIndex: 'itemDetail',
      key: 'itemDetail',
    },
  ];

  const onSearch = async (values: SearchFormValues) => {
    console.log('搜索条件:', values);
    setPagination(prev => ({ ...prev, current: 1 })); // Reset to first page on new search
    await fetchData(1, pagination.pageSize, values);
  };

  const handleExport = async () => {
    message.loading('正在导出 Excel 表格...', 0);
    const values = form.getFieldsValue();
    const params = {
      searchField: values.searchField,
      searchValue: values.matchValue,
      startTime: values.dateRange && values.dateRange[0] ? values.dateRange[0].format('YYYY-MM-DD HH:mm:ss') : undefined,
      endTime: values.dateRange && values.dateRange[1] ? values.dateRange[1].format('YYYY-MM-DD HH:mm:ss') : undefined,
    };

    try {
      const response = await axios.get('http://localhost:5233/api/Financialdetails/ExportFinancialdetails', {
        params: params,
        responseType: 'blob', // Important for handling binary data
      });

      const url = window.URL.createObjectURL(new Blob([response.data]));
      const link = document.createElement('a');
      link.href = url;
      link.setAttribute('download', '财务明细.xlsx'); // Or dynamic filename from response headers
      document.body.appendChild(link);
      link.click();
      link.remove();
      window.URL.revokeObjectURL(url);
      message.destroy();
      message.success('导出成功！');
    } catch (error) {
      console.error('导出失败:', error);
      message.destroy();
      message.error('导出失败，请检查网络或服务器！');
    }
  };

  const handleTableChange = (
    newPagination: TablePaginationConfig,
    _filters: Record<string, FilterValue | null>,
    _sorter: SorterResult<DataType> | SorterResult<DataType>[]
  ) => {
    void _filters; // Mark as intentionally unused
    void _sorter; // Mark as intentionally unused
    setPagination(prev => ({
      ...prev,
      current: newPagination.current ?? 1, // Ensure current is always a number
      pageSize: newPagination.pageSize ?? 10, // Ensure pageSize is always a number
    }));
    fetchData(newPagination.current ?? 1, newPagination.pageSize ?? 10, form.getFieldsValue());
  };

  const onFinishFailed = (errorInfo: ValidateErrorEntity) => {
    console.log('校验失败:', errorInfo);
    message.error('请填写所有必填项！');
  };

  return (
    <div style={{ padding: '20px' }}>
      <Form
        form={form}
        name="financial_details_search"
        layout="inline"
        onFinish={onSearch}
        onFinishFailed={onFinishFailed}
        initialValues={{
          searchField: 'userCode',
          type: 'all',
        }}
      >
        <Form.Item name="searchField">
          <Select style={{ width: 120 }}>
            <Option value="userCode">用户编码</Option>
            <Option value="userName">用户名</Option>
            <Option value="waybillNumber">运单号</Option>
            <Option value="remark">备注</Option>
            <Option value="operationRemark">操作备注(流水号)</Option>
          </Select>
        </Form.Item>
        <Form.Item name="matchValue">
          <Input placeholder="匹配值" />
        </Form.Item>
        <Form.Item name="dateRange">
          <RangePicker
            showTime={{ format: 'HH:mm' }}
            format="YYYY-MM-DD HH:mm"
          />
        </Form.Item>
        <Form.Item name="type">
          <Select style={{ width: 120 }} placeholder="-类型-">
            <Option value="all">-类型-</Option>
            <Option value="recharge">充值</Option>
            <Option value="consume">消费</Option>
            <Option value="consume_store">消费_门店</Option>
          </Select>
        </Form.Item>
        <Form.Item>
          <Button type="primary" htmlType="submit">
            查询
          </Button>
        </Form.Item>
        <Form.Item>
          <Button onClick={handleExport}>
            导出excel表格
          </Button>
        </Form.Item>
      </Form>

      <Space style={{ marginBottom: 16, marginTop: 20 }}></Space>

      <Table
        columns={columns}
        dataSource={data}
        loading={false} // Set loading directly to false
        pagination={false} // Managed by custom Pagination component
        onChange={handleTableChange}
        bordered
      />

      <Pagination
        style={{ marginTop: 16, textAlign: 'right' }}
        current={pagination.current}
        pageSize={pagination.pageSize}
        total={pagination.total}
        showSizeChanger
        showQuickJumper
        showTotal={(total) => `共 ${total} 条`}
        onChange={(page, pageSize) => setPagination({ ...pagination, current: page, pageSize })}
      />
    </div>
  );
};

export default Financialdetails;
